/*
 * Proto Streamer
 * Copyright (C) 2009 John Pritchard.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 */
package p.c;

import p.c.http.Connection;
import com.google.protobuf.CodedInputStream;
import com.google.protobuf.Message;
import java.io.InputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URL;

/**
 * An HTTP GET request.
 * @author jdp
 */
public class Reader
    extends Client
{
    public final static String Op = "GET";


    protected final Consumer consumer;


    public Reader(URL url, Consumer consumer)
        throws java.net.ProtocolException
    {
        super(Op,url,consumer);
        this.consumer = consumer;
        this.connection.setRequestMethod(Op);
    }


    public void run(){
        Consumer consumer = this.consumer;
        Mux mux = this.mux;
        try {
            CodedInputStream in = CodedInputStream.newInstance(this.connection.getInputStream());
            mux.enter(this,in);
            consumer.clientEnter(this);
            while (true){
                Message m = mux.read(in);
                try {
                    consumer.update(m);
                }
                catch (Exception exc){
                    exc.printStackTrace();
                }
            }
        }
        catch (IOException exc){
            PrintStream out = System.err;
            synchronized(out){
                out.print(this.getName()+' ');
                exc.printStackTrace(out);
            }
        }
        finally {
            mux.exit(this);
            consumer.clientExit(this);
        }
    }
}
